<template>
  <div style="margin: 30px;">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>商品类别</span>
      </div>
      <el-input
      placeholder="输入关键字进行过滤"
      v-model="filterText"
      style="width:300px;margin-bottom: 10px;">
      </el-input>
      <el-container>
        <el-main>
      <el-tree
      :props="tree"
      :filter-node-method="filterNode"
      :load="loadNode"
      lazy
      ref="filtertree"
      style="height:500px;">
      </el-tree>
    </el-main>
    </el-container>
    </el-card>
  </div>
</template>

<script>
import { getcategory,getparnode,getlastnode } from '@/api/index';
export default {
    name:'tree',
    data(){
      return {
        filterText: '',
        tree: {
          label: 'name',
        },
        grandata:[]
      }
    },
    watch: {
      filterText(val) {
        this.$refs.filtertree.filter(val);
      }
    },
    methods:{
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      loadNode(node, resolve) {
        //axios获取一级分类返回结果[...{id,name,level}]
        if (node.level === 0) {
          return setTimeout(() => { resolve(this.grandata);},1000)
        }
        if (node.level === 3) {return resolve([]);}
        var data
        if(node.data.level === 1){ 
          getparnode({id:node.data.id}).then(res => {
            if(res.data.status===200)  data = res.data.data
            else data = []
          }).catch(err => console.log(err))
        }else{
          getlastnode({id:node.data.id}).then(res => {
            if(res.data.status===200)  data = res.data.data
            else data = []
          }).catch(err => console.log(err))
        }
        setTimeout(() => { resolve(data);},1000)
      }
    },
    mounted(){
      getcategory().then(res => {
        this.grandata = res.data.data
      }).catch(err => console.log(err))
    }
}
</script>

<style>

</style>